/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import javax.swing.JLabel;
import logic.Cliente;

/**
 * Clase JFrameCompra encargada de mostrar las opciones de compra de los boletos. 
 * @author Victoria Fuenmayor y José Gabriel Rivera
 */
public class JFrameCompra extends javax.swing.JFrame {
    
    private GUI gui;
    private int idC=-1;
    
    /**
     * Recibe GUI como parámetro, inicializa los componentes de la clase.
     * @param gui 
     */
    public JFrameCompra(GUI gui) {
        initComponents();
        this.gui = gui;
    }
    
    /**
     * Recibe GUI y el ID del cliente, inicializa los componentes de la clase (gui, idc).
     * Crea un cliente y setea los datos del cliente en el JFrame (para ser mostrados).
     * @param gui
     * @param idC 
     */
    public JFrameCompra (GUI gui, int idC){
        initComponents();
        this.gui = gui;
        this.idC = idC;
        
        logic.Cliente cliente = (logic.Cliente) (gui.getCliente().getObject(idC));
        
        nombre.setEditable(false);
        nombre.setText(cliente.getNombre());
        idCliente.setEditable(false);
        idCliente.setText(cliente.getCedula());
        telfCliente.setEditable(false);                
        telfCliente.setText(cliente.getTelefono());
    }
    
    /**
     * Setea el numero de boleto con el parámetro indicado.
     * @param nroBoleto 
     */
    public void setNroBoleto(String nroBoleto) {
        this.nroBoleto.setText(nroBoleto);
    }

    /**
     * Setea el precio del boleto con el parámetro indicado.
     * @param precioBoleto 
     */
    public void setPrecioBoleto(String precioBoleto) {
        this.precioBoleto.setText(precioBoleto);
    }

    /**
     * Setea el total a pagar.
     * @param totalBoleto 
     */
    public void setTotalBoleto(String totalBoleto) {
        this.totalBoleto.setText(totalBoleto);
    }
   
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel = new javax.swing.JLabel();
        nombre = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        idCliente = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        telfCliente = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        precioBoleto = new javax.swing.JLabel();
        totalBoleto = new javax.swing.JLabel();
        bCompra = new javax.swing.JButton();
        bReserva = new javax.swing.JButton();
        bCancelar = new javax.swing.JButton();
        nroBoleto = new javax.swing.JLabel();

        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Ingrese sus datos");

        jLabel.setText("Nombre:");

        jLabel2.setText("Cédula:");

        jLabel3.setText("Teléfono:");

        telfCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                telfClienteActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setText("Nro. de Boletos:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("Precio unitario:");

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel6.setText("Total a pagar:");

        precioBoleto.setText("  ");

        totalBoleto.setText("  ");

        bCompra.setText("Comprar");
        bCompra.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bCompraMouseClicked(evt);
            }
        });

        bReserva.setText("Reservar");
        bReserva.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bReservaMouseClicked(evt);
            }
        });

        bCancelar.setText("Cancelar");
        bCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bCancelarMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(idCliente)
                            .addComponent(telfCliente)
                            .addComponent(nombre)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(totalBoleto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(8, 8, 8))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(18, 18, 18)
                                .addComponent(precioBoleto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel4)
                                        .addGap(18, 18, 18)
                                        .addComponent(nroBoleto, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
                                        .addComponent(jLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(62, 62, 62)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(33, 33, 33)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(bCompra)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(bReserva))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(44, 44, 44)
                                        .addComponent(bCancelar)))))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(telfCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(idCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(nroBoleto, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(precioBoleto))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(totalBoleto))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bCompra)
                    .addComponent(bReserva))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(bCancelar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void telfClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_telfClienteActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_telfClienteActionPerformed

    /**
     * MouseClicked del boton cancelar, si es presionado se oculta la ventana.
     * @param evt 
     */
    private void bCancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bCancelarMouseClicked
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_bCancelarMouseClicked

    /**
     * MouseClicked del boton de compra, si es presionado hace un llamado al método "operacionBoletos".
     * De acuerdo al ID del cliente recibido.
     * @param evt 
     */
    private void bCompraMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bCompraMouseClicked
        // TODO add your handling code here:
        if (idC == -1){
            operacionBoletos(3);
            
        }else{
            operacionBoletos(3,idC);
        }
        this.setVisible(false);
    }//GEN-LAST:event_bCompraMouseClicked

    /**
     * MouseClicked del boton de reserva, si es presionado hace un llamado al método "operacionBoletos".
     * De acuerdo al ID del cliente recibido.
     * @param evt 
     */
    private void bReservaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bReservaMouseClicked
        // TODO add your handling code here:
        if (idC == -1){
            operacionBoletos(2);
        }else{
            operacionBoletos(2, idC);
        }
        
        this.setVisible(false);
    }//GEN-LAST:event_bReservaMouseClicked

    /**
     * Recibe el estatus del boleto, asigna variables (rifa, nombre cliente, cedula y telefono).
     * Crea un cliente nuevo con los datos antes mencionados.
     * Agrega dicho cliente al arreglo de clientes.
     * Setea el ID del comprador en el ticket, así como su estado correspondiente.
     * Despresiona todos los botones presionados del PanelBotones.
     * @param status 
     */
    public void operacionBoletos(int status){
        logic.Rifa rifa = (logic.Rifa)((logic.Categoria)gui.getCategoria().getObject(gui.getListaCat().getIdCat())).getRifas().getObject(gui.getListaRifa().getIdRifa(gui.getListaCat().getIdCat()));
        String nombreCliente = nombre.getText();
        String cedula = idCliente.getText();
        String telefono = telfCliente.getText();
        
        logic.Cliente cliente = new logic.Cliente(nombreCliente, telefono, cedula, gui.getCliente().firstFree());
        gui.getCliente().addObject(cliente, cliente.getId());
                
        for(int i=0;i<gui.getPanelBoletos().getBotones().length;i++){
            if((gui.getPanelBoletos().getBotones())[i].isPressed()){
                (gui.getPanelBoletos().getBotones())[i].setColor(status);
                rifa.getTicket(i).setIdComprador(cliente.getId());
                rifa.getTicket(i).setStatus(status);
            }
        }
        gui.getPanelBoletos().letUpButtons();
    }
     
    /**
     * Recibe el estado del boleto y el ID del cliente.
     * Asigna una variable para la rifa y para el cliente.
     * Ejecuta una iteración que evalua si los botones estan presionados y estan disponibles.
     * Setea el color de los boletos de acuerdo a su estado.
     * Setea el ID del comprador en el boleto.
     * Setea el estatus del boleto.
     * Despresiona los botones de PanelBoletos
     * @param status
     * @param idC 
     */
    public void operacionBoletos(int status, int idC){
        logic.Rifa rifa = (logic.Rifa)((logic.Categoria)gui.getCategoria().getObject(gui.getListaCat().getIdCat())).getRifas().getObject(gui.getListaRifa().getIdRifa(gui.getListaCat().getIdCat()));
        logic.Cliente cliente = (logic.Cliente) (gui.getCliente().getObject(idC));

        for(int i=0;i<gui.getPanelBoletos().getBotones().length;i++){
            if((gui.getPanelBoletos().getBotones())[i].isPressed() && gui.getPanelBoletos().getBotones()[i].getStatus()==1 ){
                (gui.getPanelBoletos().getBotones())[i].setColor(status);
                rifa.getTicket(i).setIdComprador(cliente.getId());
                rifa.getTicket(i).setStatus(status);
            }
        }
        gui.getPanelBoletos().letUpButtons();
    } 
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrameCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrameCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrameCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameCompra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFrameCompra(new GUI("Raffle System")).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bCancelar;
    private javax.swing.JButton bCompra;
    private javax.swing.JButton bReserva;
    private javax.swing.JTextField idCliente;
    private javax.swing.JLabel jLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField nombre;
    private javax.swing.JLabel nroBoleto;
    private javax.swing.JLabel precioBoleto;
    private javax.swing.JTextField telfCliente;
    private javax.swing.JLabel totalBoleto;
    // End of variables declaration//GEN-END:variables
}
